import java.io.IOException;
import java.io.InputStream;

/**
 * Created by KaiseRR on 23.02.15.
 */
public class MessageReceiver extends Thread {

    private boolean isStopped;
    private InputStream in;
    private MessageCenter messageCenter;

    public MessageReceiver(InputStream in, MessageCenter messageCenter) {
        this.messageCenter = messageCenter;
        this.in = in;
        this.setDaemon(true);
    }

    public void run() {
        while (!isStopped) {
            try {
                String message = getMessage();
                if (message != null && message.length() > 0)  {
                    messageCenter.setReceivedMessage(message);
                }
            } catch (IOException e) {
                System.out.println("Client disconnected");
                stopThread();
            }
        }
    }

    public String getMessage() throws IOException {
        String result = "";
        if (in.available() > 0) {
            byte[] buff = new byte[32 * 1024];
            int length = in.read(buff);
            result = new String(buff, 0, length);

        }
        return result.toString();
    }

    public void stopThread() {
        isStopped = true;
        messageCenter.setDestroyed();
    }

    public boolean isStopped() {
        return isStopped;
    }
}
